package interaction

import (
	"errors"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/interaction"
	"github.com/flipped-aurora/gin-vue-admin/server/model/interaction/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

// UserRelationService 用户关系服务
type UserRelationService struct {
}

var UserRelationServiceApp = new(UserRelationService)

// GetUserIdByUUID 通过UUID获取用户ID
func (service *UserRelationService) GetUserIdByUUID(userUUID string) (uint, error) {
	parsedUUID, err := uuid.Parse(userUUID)
	if err != nil {
		return 0, errors.New("UUID格式错误")
	}

	var user system.SysUser
	err = global.GVA_DB.Model(&system.SysUser{}).Where("uuid = ?", parsedUUID).Select("id").First(&user).Error
	if err != nil {
		return 0, errors.New("用户不存在")
	}

	return user.ID, nil
}

// SetUserBetweenUserRelation 设置用户与用户之间关系
func (service *UserRelationService) SetUserBetweenUserRelation(fanID uint, idolID uint, relationCode int) error {
	var record interaction.UserRelation
	// 如果已经存在，修改即可
	if errors.Is(global.GVA_DB.Preload("Fan").Preload("Idol").Model(record).Where("fan_id = ? AND idol_id = ?", fanID, idolID).First(&record).Error, gorm.ErrRecordNotFound) {

		// 先检测是否存在粉丝账号与偶像账号
		var fanUser system.SysUser
		var idolUser system.SysUser

		err := global.GVA_DB.Model(&system.SysUser{}).Where("id = ?", fanID).First(&fanUser).Error
		if err != nil {
			return err
		}
		err = global.GVA_DB.Model(&system.SysUser{}).Where("id = ?", idolID).First(&idolUser).Error
		if err != nil {
			return err
		}
		// 然后插入
		record = interaction.UserRelation{
			Fan:    fanUser,
			Idol:   idolUser,
			Status: relationCode,
		}
		global.GVA_DB.Model(&interaction.UserRelation{}).Create(&record)

	} else {
		record.Status = relationCode
		global.GVA_DB.Save(&record)

	}
	return nil

}

//func (service *UserRelationService) GetUserBetweenUserRelation() (interaction.UserRelation, error) {

// GetUserRelationList 获取用户关系列表
func (service *UserRelationService) GetUserRelationList(selfId uint, params request.PageInfo, queryMode int) ([]response.UserRelationResponse, int64, error) {
	limit := params.PageSize
	offset := params.PageSize * (params.Page - 1)
	db := global.GVA_DB.Model(&interaction.UserRelation{})
	var result []interaction.UserRelation
	var total int64
	switch queryMode {
	case interaction.Fan:
		db.Where("idol_id = ?", selfId)
		break
	case interaction.Idol:
		db.Where("fan_id = ?", selfId)
		break
	default:
		break
	}

	db.Count(&total)
	err := db.Preload("Fan", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, created_at, updated_at, uuid, username, nick_name, header_img, phone, email")
	}).Preload("Idol", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, created_at, updated_at, uuid, username, nick_name, header_img, phone, email")
	}).Limit(limit).Offset(offset).Find(&result).Error

	// 转换为响应模型
	responseResult := make([]response.UserRelationResponse, len(result))
	for i, relation := range result {
		responseResult[i] = response.UserRelationResponse{
			FanID:  relation.FanID,
			IdolID: relation.IdolID,
			Fan: response.SimpleUser{
				UUID:      relation.Fan.UUID,
				Username:  relation.Fan.Username,
				NickName:  relation.Fan.NickName,
				HeaderImg: relation.Fan.HeaderImg,
				Phone:     relation.Fan.Phone,
				Email:     relation.Fan.Email,
			},
			Idol: response.SimpleUser{
				UUID:      relation.Idol.UUID,
				Username:  relation.Idol.Username,
				NickName:  relation.Idol.NickName,
				HeaderImg: relation.Idol.HeaderImg,
				Phone:     relation.Idol.Phone,
				Email:     relation.Idol.Email,
			},
			Status: relation.Status,
		}
	}

	return responseResult, total, err

	//db.Where("fan_id ")

}
